import { defineStore } from 'pinia';
import { login, logout, getUserInfo, updateUserInfo } from '@/api/auth';
import notificationWebSocket from '@/utils/websocket';

export const useUserStore = defineStore('user', {
  state: () => {
    // 尝试从localStorage获取用户信息
    let userInfo = null;
    try {
      const storedUserInfo = localStorage.getItem('userInfo');
      if (storedUserInfo) {
        userInfo = JSON.parse(storedUserInfo);
      }
    } catch (e) {
      console.error('Failed to parse stored user info', e);
    }
    
    return {
      userInfo,
      isLoggedIn: !!localStorage.getItem('satoken')
    };
  },
  
  actions: {
    async login(credentials) {
      try {
        const res = await login(credentials);
        
        // 更新登录状态和用户信息
        this.isLoggedIn = !!localStorage.getItem('satoken');
        
        // 如果登录响应中包含用户信息，直接使用
        if (res && res.user) {
          this.userInfo = res.user;
          
          // 登录成功后连接WebSocket
          if (this.userInfo.id) {
            notificationWebSocket.connect(this.userInfo.id);
          }
        } else {
          // 否则尝试获取用户信息
          await this.getUserInfo();
        }
        
        return res;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    
    async logout() {
      try {
        // 登出前关闭WebSocket连接
        notificationWebSocket.close();
        
        await logout();
        this.clearUserState();
      } catch (error) {
        // 即使后端登出失败，也清除本地状态
        this.clearUserState();
        return Promise.reject(error);
      }
    },
    
    clearUserState() {
      localStorage.removeItem('satoken');
      localStorage.removeItem('tokenName');
      localStorage.removeItem('userInfo');
      this.userInfo = null;
      this.isLoggedIn = false;
    },
    
    async getUserInfo() {
      try {
        if (!localStorage.getItem('satoken')) return null;
        
        // 尝试从localStorage获取用户信息
        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedUserInfo) {
          try {
            this.userInfo = JSON.parse(storedUserInfo);
            return this.userInfo;
          } catch (e) {
            console.error('Failed to parse stored user info', e);
          }
        }
        
        // 如果没有存储的用户信息或解析失败，从服务器获取
        const res = await getUserInfo();
        if (res) {
          this.userInfo = res;
          localStorage.setItem('userInfo', JSON.stringify(res));
        }
        return res;
      } catch (error) {
        this.clearUserState();
        return Promise.reject(error);
      }
    },
    
    // 更新头像
    async updateAvatar(avatarUrl) {
      if (!this.userInfo) return;
      
      // 更新用户信息中的头像
      this.userInfo.avatar = avatarUrl;
      
      // 更新localStorage中的用户信息
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
      
      // 也可以调用后端API同步更新
      try {
        await updateUserInfo({ avatar: avatarUrl });
      } catch (error) {
        console.error('Failed to sync avatar update with server', error);
      }
    },
    
    // 检查登录状态
    checkLogin() {
      this.isLoggedIn = !!localStorage.getItem('satoken');
      
      // 如果已登录但没有用户信息，尝试获取
      if (this.isLoggedIn && !this.userInfo) {
        this.getUserInfo().catch(() => {
          this.isLoggedIn = false;
        });
      }
      
      return this.isLoggedIn;
    }
  }
}); 